<?php

/**
 * WeEngine System
 *
 * (c) We7Team 2021 <https://www.w7.cc>
 *
 * This is not a free software
 * Using it under the license terms
 * visited https://www.w7.cc for more details
 */

namespace App\Http\Controllers;

use App\Exceptions\LogicErrorException;
use App\Http\Logic\PayLogic;
use App\Http\Validator\UserValidate;
use App\Models\PayLog;
use Illuminate\Http\Request;
use Itwmw\Validate\Attributes\Validator;

class PayController
{
    public function notify(Request $request)
    {
        $data = $request->post();
        $sign = $data['notify_sign'] ?? '';
        if (empty($sign)) {
            throw new LogicErrorException('签名失败');
        }

        unset($data['notify_sign']);
        if ($sign !== PayLogic::getSignForContent($data)) {
            throw new LogicErrorException('签名失败');
        }

        $outTradeNo = $data['out_trade_no'];

        $pay = PayLog::query()
            ->where('out_trade_no', $outTradeNo)
            ->where('pay_type', $data['pay_type'])
            ->where('account_id', $data['account_id'])
            ->first();

        if (0 == $pay->status) {
            $pay->status = 1;
            $pay->save();
        }

        return 'success';
    }

    #[Validator(validate:UserValidate::class, fields: ['page'])]
    public function list(Request $request)
    {
        $page = get_validate_data($request)->get('page', 0);
        $data = PayLog::query()
            ->orderByDesc('created_at')
            ->paginate(columns:['id', 'account_id', 'out_trade_no', 'pay_type', 'amount', 'status', 'created_at'], page: $page);
        return json_success('', $data->toArray());
    }
}
